<template>
  <div>
    <transition name="el-zoom-in-center">
      <div class="jsbos-preview-main user-form">
        <div class="jsbos-common-page-header">
          <el-page-header @back="goBack" content="编辑" />
          <div class="options">
            <el-button v-if="activeIndex == 1" type="primary" @click="beforStep"
              >上一步
            </el-button>
            <el-button type="primary" @click="nextOrSave">{{
              activeIndex == 0 ? "下一步" : "保存"
            }}</el-button>
            <el-button @click="goBack"
              >{{ $t("common.cancelButton") }}
            </el-button>
          </div>
        </div>
        <div class="main" v-loading="false">
          <div class="jsbos-common-layout-main jsbos-flex-main">
            <el-steps
              :active="activeIndex"
              finish-status="success"
              simple
              style="margin-top: 20px"
            >
              <el-step title="场景配置"> </el-step>
              <el-step title="模板配置"></el-step>
            </el-steps>
            <el-form
              ref="elForm1"
              :model="dataForm"
              size="small"
              :rules="rules1"
              label-width="110px"
              label-position="right"
            >
              <div class="data_form_content" v-if="activeIndex == 0">
                <el-row :gutter="15" class="">
                  <template>
                    <el-col :span="12">
                      <el-form-item label="名称:" prop="fullName">
                        <el-input
                          show-word-limit
                          v-model.trim="dataForm.fullName"
                          placeholder="请输入"
                          clearable
                          :disabled="!ifAdd"
                          :style="{ width: '100%' }"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="编码:" prop="enCode">
                        <el-input
                          show-word-limit
                          v-model.trim="dataForm.enCode"
                          placeholder="请输入"
                          clearable
                          :disabled="!ifAdd"
                          :style="{ width: '100%' }"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="消息类型:" prop="business.category">
                        <el-select
                          v-model="dataForm.business.category"
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in categoryOptions"
                            :key="index"
                            :label="item.fullName"
                            :value="item.enCode"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="业务系统:" prop="taskCode">
                        <el-select
                          :disabled="!ifAdd"
                          v-model="dataForm.taskCode"
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in taskCodeOptions"
                            :key="index"
                            :label="item.fullName"
                            :value="item.enCode"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="描述" prop="description">
                        <el-input
                          v-model="dataForm.description"
                          placeholder="请输入"
                          :style="{ width: '100%' }"
                          true
                          type="textarea"
                          :autosize="{ minRows: 1, maxRows: 4 }"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label-width="0">
                        <div class="jsbos-common-title">
                          <h2>关键词</h2>
                        </div>
                        <el-table
                          :data="dataForm.business.keywordList"
                          size="mini"
                        >
                          <el-table-column
                            type="index"
                            width="50"
                            label="序号"
                            :align="'center'"
                          />
                          <el-table-column prop="enCode" label="参数名">
                            <template slot="header">
                              <span class="required-sign">*</span>参数名
                            </template>
                            <template slot-scope="scope">
                              <el-input
                                :readonly="!scope.row.closable"
                                v-model="scope.row.enCode"
                                placeholder="请输入"
                                clearable
                                :style="{ width: '100%' }"
                              >
                              </el-input>
                            </template>
                          </el-table-column>
                          <el-table-column prop="fullName" label="注释">
                            <template slot="header">
                              <span class="required-sign">*</span>注释
                            </template>
                            <template slot-scope="scope">
                              <el-input
                                :readonly="!scope.row.closable"
                                v-model="scope.row.fullName"
                                placeholder="请输入"
                                clearable
                                :style="{ width: '100%' }"
                              >
                              </el-input>
                            </template>
                          </el-table-column>
                          <el-table-column prop="example" label="示例">
                            <template slot-scope="scope">
                              <el-input
                                v-model="scope.row.example"
                                placeholder="请输入"
                                clearable
                                :style="{ width: '100%' }"
                              >
                              </el-input>
                            </template>
                          </el-table-column>
                          <el-table-column label="操作" width="50">
                            <template slot-scope="scope">
                              <el-button
                                v-show="scope.row.closable"
                                size="mini"
                                type="text"
                                class="jsbos-table-delBtn"
                                @click="delKeywordList(scope.$index)"
                                >删除</el-button
                              >
                            </template>
                          </el-table-column>
                        </el-table>
                        <div class="table-actions" @click="addKeywordList()">
                          <el-button type="text" icon="el-icon-plus"
                            >添加</el-button
                          >
                        </div>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-row>
              </div>
              <div class="data_form_content" v-else>
                <el-tabs
                  v-model="editableTabsValue"
                  type="card"
                  addable
                  @tab-remove="handleTabRemove"
                  @tab-add="handleTabsAdd"
                  @tab-click="handleClick"
                >
                  <template v-for="(data, i) in dataForm.templateList">
                    <el-tab-pane
                      :label="data.messageTypeName"
                      :name="i + ''"
                      :key="i"
                      :closable="data.id ? false : true"
                    >
                      <div class="">
                        <el-row :gutter="15" class="">
                          <!-- <el-form
                          ref="elForm2"
                          :rules="rules2"
                          :model="data"
                          size="small"
                          label-width="100px"
                          label-position="right"
                        > -->
                          <el-col :span="12">
                            <el-form-item
                              label="启用状态"
                              :prop="`templateList.${i}.sendEnabledMark`"
                            >
                              <span slot="label">
                                <el-tooltip
                                  content="控制消息模板是否加入发送配置"
                                  placement="top"
                                >
                                  <i
                                    class="icon-ym icon-ym-header-about"
                                    style="font-size: 14px"
                                  ></i>
                                </el-tooltip>
                                启用状态
                              </span>
                              <el-switch
                                v-model="data.sendEnabledMark"
                                :active-value="1"
                                :inactive-value="0"
                                @change="sendEnabledMarkChange"
                              >
                              </el-switch>
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item
                              label="消息渠道"
                              :prop="`templateList.${i}.messageType`"
                              :rules="rules2.messageType"
                            >
                              <el-select
                                v-model="data.messageType"
                                placeholder="请选择"
                                @change="messageTypeChange"
                              >
                                <el-option
                                  v-for="(item, index) in messageTypeOptions"
                                  :key="index"
                                  :label="item.fullName"
                                  :value="item.enCode"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item
                              label="应用名称"
                              v-if="
                                data.sendEnabledMark == 1 &&
                                data.messageType != 1
                              "
                              :prop="`templateList.${i}.accountConfigIds`"
                              :rules="rules2.accountConfigIds"
                            >
                              <MsgAccountDialog
                                :accountConfigIds="data.accountConfigIds"
                                :title="data.accountNames"
                                :messageType="data.messageType"
                                @table-change="getAccountChange"
                                :clearable="false"
                              />
                            </el-form-item>
                          </el-col>
                          <el-col :span="24">
                            <!-- 站内信 -->
                            <FormSys
                              v-if="['1'].includes(data.messageType)"
                              ref="FormSysRef"
                              v-model="dataForm.templateList[i]"
                              :labelWidth="labelWidth"
                              :keywordList="dataForm.business.keywordList"
                            ></FormSys>
                            <FormEmail
                              v-if="
                                ['2', '4', '5', '8'].includes(data.messageType)
                              "
                              ref="FormEmailRef"
                              v-model="dataForm.templateList[i]"
                              :labelWidth="labelWidth"
                              :keywordList="dataForm.business.keywordList"
                            ></FormEmail>
                            <FormSms
                              v-if="['3'].includes(data.messageType)"
                              ref="FormSmsRef"
                              v-model="dataForm.templateList[i]"
                              :labelWidth="labelWidth"
                              :keywordList="dataForm.business.keywordList"
                            ></FormSms>
                            <FormWxxcx
                              v-if="['6'].includes(data.messageType)"
                              ref="FormWxxcxRef"
                              v-model="dataForm.templateList[i]"
                              :labelWidth="labelWidth"
                              :keywordList="dataForm.business.keywordList"
                            ></FormWxxcx>
                            <FormWxgzh
                              v-if="['7'].includes(data.messageType)"
                              ref="FormWxgzhRef"
                              v-model="dataForm.templateList[i]"
                              :labelWidth="labelWidth"
                              :keywordList="dataForm.business.keywordList"
                            ></FormWxgzh>
                          </el-col>
                          <!-- </el-form> -->
                        </el-row>
                      </div>
                    </el-tab-pane>
                  </template>
                </el-tabs>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import { getInfo, Update, Create } from "../api/mcMsgSendAggregation.js";
import FormSys from "../mcMsgTemplate/FormSys.vue";
import FormEmail from "../mcMsgTemplate/FormEmail.vue";
import FormWxgzh from "../mcMsgTemplate/FormWxgzh.vue";
import FormWxxcx from "../mcMsgTemplate/FormWxxcx.vue";
import FormSms from "../mcMsgTemplate/FormSms.vue";
import MsgAccountDialog from "./msgAccountDialog.vue";
export default {
  components: {
    FormSys,
    FormEmail,
    FormWxgzh,
    FormWxxcx,
    FormSms,
    MsgAccountDialog,
  },
  props: {
    taskCode: {
      type: String,
      default: "",
    },
    ifAdd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      labelWidth: "100px",
      editableTabsValue: 0,
      messageTypeOptions: [],
      categoryOptions: [],
      taskCodeOptions: [],
      inputVisible: false,
      inputValue: "",
      activeIndex: 0,
      keywordList: [],
      dataForm: {
        fullName: "",
        enCode: "",
        taskCode: "",
        description: "",
        category: undefined,
        business: {
          category: "",
          keywordList: [],
        },
        keywordList: [],
        templateList: [],
      },
      itemKey: Math.random(),
      templateData: {
        messageType: undefined,
        fieldList: [],
        sendTemplateList: [],
        childForm: this.childForm,
        accountConfigIds: [],
        accountNames: undefined,
        sendEnabledMark: 1,
      },
      childForm: {
        title: "",
        content: "",
        templateCode: "",
        wxSkip: "",
        xcxAppId: "",
        subscriberType: "",
        fieldList: [],
      },
      // childForm: [],
      dataId: null,
      showHideState: true,
      rules1: {
        "business.category": [
          { required: true, message: "请选择消息类型", trigger: "change" },
        ],
        fullName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        enCode: [{ required: true, message: "请输入编码", trigger: "blur" }],
      },
      rules2: {
        messageType: [
          { required: true, message: "请选择消息渠道", trigger: "change" },
        ],
        accountConfigIds: [
          { required: true, message: "请选择应用名称", trigger: "change" },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getMessageTypeOptions();
    this.getcategoryOptions();
    this.getTaskCodeOptions();
  },
  mounted() {},
  methods: {
    getTaskCodeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "taskCode",
        })
        .then((res) => {
          this.taskCodeOptions = res;
        });
    },
    getcategoryOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "msgType",
        })
        .then((res) => {
          this.categoryOptions = res;
        });
    },
    getMessageTypeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "msgSendType",
        })
        .then((res) => {
          this.messageTypeOptions = res;
        });
    },

    // 初始化数据
    init(id, fullName, enCode) {
      if (id) {
        this.dataId = id;
        let that = this;
        getInfo(id).then((res) => {
          this.dataForm = res.data;
          that.dataForm.templateList.forEach((item) => {
            item.sendEnabledMark = parseInt(
              item.sendEnabledMark ? item.sendEnabledMark : 1
            );
            // item.keywordList = that.dataForm.business.keywordList;
            // that.messageTypeOptions.forEach((el) => {
            //   if (item.messageType == el.enCode) {
            //     item.messageTypeName = el.fullName;
            //   }
            // });
            item.fieldList.forEach((el) => {
              // 渠道消息模板 变量关联选项
              el.keywordList = this.dataForm.business.keywordList;
            });
            // 封装 不同渠道消息模板子组件表单数据
            var _childForm = {
              title: item.title,
              content: item.content,
              templateCode: item.templateCode,
              wxSkip: item.wxSkip,
              xcxAppId: item.xcxAppId,
              subscriberType: item.subscriberType,
              fieldList: item.fieldList,
              // messageType: item.messageType,
              // messageTypeName: item.messageTypeName,
            };
            this.$set(item, "childForm", _childForm);
            // this.childForm.push();
            // 发送配置 关联渠道消息模板和应用授权账号
            let _yyName = "";
            let _yyId = [];
            item.sendTemplateList.forEach((el) => {
              _yyName = _yyName + el.accountName + "，";
              _yyId.push(el.accountConfigId);
            });
            _yyName = _yyName.substring(0, _yyName.length - 1);
            item.accountNames = _yyName;
            item.accountConfigIds = _yyId;
          });

          // this.keywordList = this.dataForm.business.keywordList;
          // let _dataAll = this.dataForm.templateList[0];
          // this.templateData = this.dataForm.templateList[0];
        });
      } else {
        this.dataForm.taskCode = this.taskCode;
        this.dataForm.fullName = fullName;
        this.dataForm.enCode = enCode;
        this.dataForm.templateList = [this.templateData];
        // this.dataForm.templateList.push({
        //   messageType: this.messageTypeOptions[0].enCode,
        //   messageTypeName: this.messageTypeOptions[0].fullName,
        // });
        // this.childForm = {
        //   messageType: this.messageTypeOptions[0].enCode,
        //   messageTypeName: this.messageTypeOptions[0].fullName,
        // };
        // this.childForm = [];
        // this.childForm.push({
        //   messageType: this.messageTypeOptions[0].enCode,
        //   messageTypeName: this.messageTypeOptions[0].fullName,
        //   title: "",
        //   content: "",
        //   templateCode: "",
        //   wxSkip: "",
        //   xcxAppId: "",
        //   subscriberType: "",
        //   fieldList: [],
        // });
        // this.keywordList = this.dataForm.business.keywordList;
        // this.templateData = this.dataForm.templateList[0];
      }
    },
    // 添加 消息场景关键词
    addKeywordList() {
      let item = {
        fullName: undefined,
        enCode: undefined,
        example: undefined,
        closable: true,
      };
      this.dataForm.business.keywordList.push(item);
    },
    // 删除 消息场景关键词
    delKeywordList(index) {
      this.dataForm.business.keywordList.splice(index, 1);
    },
    // 上一步
    beforStep() {
      this.activeIndex = 0;
    },
    // 下一步 或 保存
    nextOrSave() {
      if (this.activeIndex == 0) {
        this.$refs["elForm1"].validate((valid) => {
          if (valid) {
            this.activeIndex = 1;
          } else {
            return false;
          }
        });
      } else {
        this.$refs["elForm1"].validate((valid) => {
          if (valid) {
            if (this.dataId) {
              var _data = this.dataList();
              Update(_data).then((res) => {
                this.$message({
                  message: "保存成功！",
                  type: "success",
                });
                this.activeIndex = 0;
                this.$emit("close", true);
              });
            } else {
              var _data = this.dataList();
              Create(_data).then((res) => {
                this.$message({
                  message: "保存成功！",
                  type: "success",
                });
                this.activeIndex = 0;
                this.$emit("close", true);
              });
            }
          } else {
            this.$message({
              message: "表单校验未通过",
              type: "warning",
            });
          }
        });
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      for (let i = 0; i < _data.templateList.length; i++) {
        var _templateData = _data.templateList[i];
        var accountConfigIds = _templateData.accountConfigIds;
        if (_templateData.messageType != "1" && accountConfigIds) {
          var _sendTemplateList = [];
          accountConfigIds.forEach((item, index) => {
            _sendTemplateList.push({ accountConfigId: item });
          });
          _templateData.sendTemplateList = _sendTemplateList;
        } else {
          _templateData.sendTemplateList = [{ accountConfigId: undefined }];
        }
        _templateData = Object.assign(
          {},
          _templateData,
          _templateData.childForm
        );
      }
      return _data;
    },
    // 渠道消息模板 页签新增
    handleTabsAdd() {
      this.dataForm.templateList.push(this.templateData);
      this.editableTabsValue = JSON.stringify(
        this.dataForm.templateList.length - 1
      );
    },
    handleTabRemove(targetName) {
      this.dataForm.templateList.splice(targetName, 1);
      this.editableTabsValue = JSON.stringify(
        this.dataForm.templateList.length - 1
      );
    },
    // 渠道消息模板 页签新增
    handleTabsEdit(targetName, action) {
      if (action == "add") {
        this.dataForm.templateList.push(this.templateData);
        // this.handleClick({ index: this.dataForm.templateList.length - 1 });
      }
      if (action === "remove") {
        this.dataForm.templateList.splice(targetName, 1);
        // this.handleClick({ index: this.dataForm.templateList.length - 1 });
      }
      this.editableTabsValue = JSON.stringify(
        this.dataForm.templateList.length - 1
      );
    },
    // 渠道消息模板 页签选中点击
    handleClick(tab, event) {
      // let that = this;
      // this.showHideState = false;
      // this.keywordList = this.dataForm.business.keywordList;
      // let _dataAll = this.dataForm.templateList[tab.index];
      // this.templateData = this.dataForm.templateList[tab.index];
      // setTimeout(function () {
      //   that.showHideState = true;
      // }, 100);
      //
    },
    // 启用状态change事件
    sendEnabledMarkChange(val) {
      var _templateData = this.dataForm.templateList[this.editableTabsValue];
      _templateData.accountConfigIds = [];
      _templateData.accountNames = "";
    },
    // 消息渠道change事件
    messageTypeChange(val) {
      var _templateData = this.dataForm.templateList[this.editableTabsValue];
      _templateData.accountConfigIds = [];
      _templateData.accountNames = "";
      this.$set(_templateData, "childForm", this.childForm);
      this.messageTypeOptions.forEach((item) => {
        if (item.enCode == val) {
          _templateData.messageTypeName = item.fullName;
        }
      });
    },
    // 应用授权 change事件
    getAccountChange(multipleSelection) {
      var _templateData = this.dataForm.templateList[this.editableTabsValue];
      let _accountNames = "";
      let _accountConfigIds = [];
      multipleSelection.forEach((item) => {
        _accountNames = _accountNames + item.fullName + "，";
        _accountConfigIds.push(item.id);
      });
      _accountNames = _accountNames.substring(0, _accountNames.length - 1);
      this.$set(_templateData, "accountNames", _accountNames);
      this.$set(_templateData, "accountConfigIds", _accountConfigIds);
      this.dataForm.templateList[this.editableTabsValue] = _templateData;
      this.$forceUpdate();
    },

    goBack() {
      this.activeIndex = 0;
      this.$emit("close", true);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-checkbox-button.is-disabled.is-checked .el-checkbox-button__inner {
  color: #ffffff;
  background-color: #1890ff;
  border-color: #1890ff;
  -webkit-box-shadow: -1px 0 0 0 #74bcff;
  box-shadow: -1px 0 0 0 #74bcff;
}
.data_form_content {
  padding: 20px;
  >>> .el-select {
    width: 100%;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px !important;
  height: 28px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
  >>> .el-input--small .el-input__inner {
    line-height: 28px !important;
    height: 28px !important;
  }
}
</style>
